/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package battleship;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.TreeSet;
import javax.swing.JButton;

/**
 *
 * @author Tomek
 */
public class SetShipFieldActionListener implements ActionListener{
	public TreeSet<Field> set= new TreeSet<Field>();
	public GameCreatorPanel gcp;
	public int actualShipSize;
	public JButton doneButton;
	boolean curvedShipsAllowed;
	@Override
	public void actionPerformed(ActionEvent e) {
		Field t = (Field) e.getSource();
		switch (t.fieldType) {
			case NORMAL:
				if(gcp.shipsInDocks.getSelectedRow()<0) return;
				if(set.isEmpty()){
					actualShipSize = (Integer)gcp.shipsInDocks.getValueAt(gcp.shipsInDocks.getSelectedRow(), 0);
					gcp.shipsInDocks.setEnabled(false);
					set.add(t);
					t.changeType(FieldType.SET);
				}else{
					if(set.size()==actualShipSize) break;
					if(curvedShipsAllowed || set.size()==1){
						for(Field f: set){
							if(!f.isNeighbour(t))continue;
							set.add(t);
							t.changeType(FieldType.SET);
							break;
						}
					}else{
						int row = set.first().row;
						int col = set.first().col;
						Field f = set.last();
						if(f.row == row) col = -1; else row = -1;
						if(row>-1){
							if(t.row!=row) return;
						}else{
							if(t.col!=col) return;
						}
						for(Field g: set){
							if(!t.isNeighbour(g)) continue;
							set.add(t);
							t.changeType(FieldType.SET);
							break;
						}
					}
				}
				if(set.size()==actualShipSize) doneButton.setEnabled(true);
				break;
			case SET:
				if(set.size()>1){
					set.remove(t);
					if(t.getReachable(set,0, true).size()!=set.size()){
						set.add(t);
						break;
					}
				}
				t.changeType(FieldType.NORMAL);
				set.remove(t);
				doneButton.setEnabled(false);
				if(set.isEmpty()){
					gcp.shipsInDocks.setEnabled(true);
				}
				break;
		}
	}
}
